<?php
// +---------------------------------------------------------------------+
// | NiuCloud | [ WE CAN DO IT JUST NiuCloud ]                |
// +---------------------------------------------------------------------+
// | Copy right 2019-2029 www.niucloud.com                          |
// +---------------------------------------------------------------------+
// | Author | NiuCloud <niucloud@outlook.com>                       |
// +---------------------------------------------------------------------+
// | Repository | https://github.com/niucloud/framework.git          |
// +---------------------------------------------------------------------+

namespace addon\wxoplatform\model;

use app\model\BaseModel;
use app\model\system\Api;
use app\model\system\Config as ConfigModel;
use app\model\system\Cron;

/**
 * 微信公众号配置
 */
class Weapp extends BaseModel
{
    protected $audit_status = [
          0 => '审核中',
          1 => '审核成功',
          2 => '审核被拒绝',
          3 => '审核延后',
          4 => '已撤回',
          5 => '已发布'
    ];

    /**
     * 获取审核记录
     * @param array $condition
     * @param bool $field
     * @param string $order
     * @param int $page
     * @param int $list_rows
     */
    public function getAuditPageList($site_id, $condition = [], $field = true, $order = '', $page = 1, $list_rows = PAGE_LIST_ROWS){
        $list = model('weapp_audit_record')->pageList($condition, $field, $order, $page, $list_rows);
        if (!empty($list['list'])) {
            $platform = new OpenPlatform($site_id);
            foreach ($list['list'] as $k => $item) {
                if ($item['status'] == 0 || $item['status'] == 3) {
                    $audit_status = $platform->getAuditstatus( ['auditid' => $item['auditid'] ] );
                    if ($audit_status['code'] >= 0 && $audit_status['data']['status'] != 2) {
                        $this->updateAuditStatus($item['id'], $audit_status['data']);
                    }
                }
                $list['list'][$k]['status_name'] = $this->audit_status[ $item['status'] ] ?? '';
            }
        }
        return $this->success($list);
    }

    /**
     * 变更审核状态
     * @param $id
     * @param $data
     */
    private function updateAuditStatus($id, $param){
        $data = [];
        switch ($param['status']) {
            case 0: // 审核通过
                    $data = [
                        'status' => 1,
                        'audit_time' => time()
                    ];
                break;
            case 1: // 审核未通过
                $data = [
                    'status' => 2,
                    'audit_time' => time(),
                    'reason' => $param['reason']
                ];
                break;
            case 4: // 审核延后
                $data = [
                    'status' => 3,
                    'reason' => $param['reason']
                ];
                break;
        }
        if (!empty($data)) {
            model('weapp_audit_record')->update($data, [ ['id', '=', $id] ]);
        }
    }

    /**
     * 撤销审核
     * @param $id
     * @param $site_id
     */
    public function cancelAudit($id, $site_id){
        $audit_info = model('weapp_audit_record')->getInfo([ ['id', '=', $id],['site_id', '=', $site_id], ['status', '=', 0] ]);
        if (empty($audit_info)) return $this->error();

        $platform = new OpenPlatform($site_id);
        $result = $platform->undocodeaudit([ 'auditid' => $audit_info['auditid'] ]);
        if ($result['code'] < 0) return $result;

        model('weapp_audit_record')->update([ 'status' => 4 ], [ ['id', '=', $id],['site_id', '=', $site_id] ]);
        return $this->success('', 'CANCEL_SUCCESS');
    }

    /**
     * 小程序发布
     * @param $id
     * @param $site_id
     * @return array
     */
    public function release($id, $site_id){
        $audit_info = model('weapp_audit_record')->getInfo([ ['id', '=', $id],['site_id', '=', $site_id], ['status', '=', 1] ]);
        if (empty($audit_info)) return $this->error();

        $platform = new OpenPlatform($site_id);
        $result = $platform->release();
        if ($result['code'] < 0) return $result;

        model('weapp_audit_record')->update([ 'status' => 5, 'release_time' => time() ], [ ['id', '=', $id],['site_id', '=', $site_id] ]);
        return $this->success('', 'RELEASE_SUCCESS');
    }

    /**
     * 获取体验者列表
     * @param array $condition
     * @param bool $field
     * @param string $order
     * @param int $page
     * @param int $list_rows
     */
    public function getExperiencerPageList($condition = [], $field = true, $order = '', $page = 1, $list_rows = PAGE_LIST_ROWS){
        $list = model('weapp_experiencer')->pageList($condition, $field, $order, $page, $list_rows);
        return $this->success($list);
    }

    /**
     *  绑定体验者
     * @param $data
     */
    public function bindExperiencer($site_id, $wechatid){
        $platform = new OpenPlatform($site_id);
        $result = $platform->bindTester(['wechatid' => $wechatid]);
        if ($result['code'] < 0) return $result;

        $data = [
            'site_id' => $site_id,
            'wechatid' => $wechatid,
            'userstr' => $result['data']['userstr'],
            'create_time' => time()
        ];
        $result = model('weapp_experiencer')->add($data);
        return $this->success($result);
    }

    /**
     * 体验者取消绑定
     * @param $id
     * @param $site_id
     */
    public function unbindExperiencer($id, $site_id){
        $experiencer_info = model('weapp_experiencer')->getInfo([ ['id', '=', $id],['site_id', '=', $site_id] ]);
        if (empty($experiencer_info)) return $this->error();

        $platform = new OpenPlatform($site_id);
        $result = $platform->unbindTester(['userstr' => $experiencer_info['userstr'] ]);
        if ($result['code'] < 0) return $result;

        model('weapp_experiencer')->delete([ ['id', '=', $id],['site_id', '=', $site_id] ]);
        return $result;
    }

    /**
     * 检测小程序模板是否发生了变更
     */
    public function checkWeappVersionIsChange($template_info){
        $config = new ConfigModel();
        $weapp_version_info = $config->getConfig([['site_id', '=', 0], ['app_module', '=', 'admin'], ['config_key', '=', 'OPLATFORM_WEAPP_VERSION']]);
        $weapp_version_info = $weapp_version_info['data']['value'];
        if (empty($weapp_version_info) || $weapp_version_info['template_id'] != $template_info['template_id']) {
            $cron = new Cron();
            $cron->addCron(1,0,'小程序代码自动上传', 'WeappAutoSubmit', (time() + 30), 0);
            $config->setConfig($template_info, '开放平台最新小程序模板信息', 1, [['site_id', '=', 0], ['app_module', '=', 'admin'], ['config_key', '=', 'OPLATFORM_WEAPP_VERSION']]);
        }
    }

    /**
     * 小程序自动提交审核
     */
    public function autoSubmitAudit(){
        set_time_limit(0);
        // 小程序授权的站点
        $site_list = model('config')->getList([ ['app_module', '=', 'shop'], ['config_key', '=', 'WEAPP_CONFIG' ], ['value', 'like', '%is_authopen%'] ], 'site_id');

        // 获取最新的一条模板
        $platform = new OpenPlatform();
        $template_list = $platform->getTemplateList();
        if ($template_list['code'] == 0 && is_array($template_list['data']) && count($template_list['data']) > 1) array_multisort(array_column($template_list['data'], 'template_id'), SORT_DESC, $template_list['data']);
        $template_info = $template_list['data'][0] ?? [];

        if (!empty($site_list) && $template_info) {
            // api安全配置
            $api_model = new Api();
            $api_config = $api_model->getApiConfig();
            $api_config =$api_config['data'];

            foreach ($site_list as $site_item) {
                $platform = new OpenPlatform($site_item['site_id']);
                $socket_url = (strstr(ROOT_URL, 'https://') === false ? str_replace('http', 'ws', ROOT_URL) : str_replace('https', 'wss', ROOT_URL)) . '/wss';
                $data = array(
                    'template_id' => $template_info['template_id'],
                    'ext_json' => [
                        'extEnable' => true,
                        'extAppid' => $platform->appid,
                        'ext' => [
                            'siteId' => $site_item['site_id'],
                            'baseUrl' => __ROOT__,
                            'imgDomain' => __ROOT__,
                            'apiSecurity' => $api_config['is_use'] ?? 0,
                            'publicKey' => $api_config['value']['public_key'] ?? '',
                            'webSocket' => $socket_url
                        ]
                    ],
                    'user_version' => $template_info['user_version'],
                    'user_desc' => $template_info['user_desc'] . '，上传时间'.date('Y-m-d H:i:s', time())
                );
                $platform->weappCommit($data);
            }
        }
    }

    /**
     * 下载小程序源码
     */
    public function download(){
        $source_file_path = 'public/weapp';
        $file_arr = getFileMap($source_file_path);

        if (!empty($file_arr)) {
            $zipname = 'weapp_' . date('YmdHi') . '.zip';

            $zip = new \ZipArchive();
            $res = $zip->open($zipname, \ZipArchive::CREATE);
            if ($res === TRUE) {
                foreach ($file_arr as $file_path => $file_name) {
                    if (is_dir($file_path)) {
                        $file_path = str_replace($source_file_path . '/', '', $file_path);
                        $zip->addEmptyDir($file_path);
                    } else {
                        $zip_path = str_replace($source_file_path . '/', '', $file_path);
                        $zip->addFile($file_path, $zip_path);
                    }
                }
                $zip->close();

                header("Content-Type: application/zip" );
                header("Content-Transfer-Encoding: Binary" );
                header("Content-Length: " . filesize ($zipname) );
                header("Content-Disposition: attachment; filename=\"" . basename ($zipname) . "\"" );
                readfile($zipname);
                @unlink($zipname);
            }
        }
    }
}